package com.sdkj.fixed.asset.hc.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.hc.vo.in.IdParams;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptOutGetPageParams;
import com.sdkj.fixed.asset.api.hc.vo.out.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.mapper.*;
import com.sdkj.fixed.asset.pojo.hc.*;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import com.sdkj.fixed.asset.pojo.system.UserDateAuth;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.aspectj.apache.bcel.classfile.Code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/***
 *
 * @author scx
 *
 */
@Service
public class ReceiptOutService extends BaseService<ReceiptOut> {

    private static Logger log = LoggerFactory.getLogger(ReceiptOutService.class);

    @Resource
    private ReceiptOutMapper mapper;

    @Resource
    private ReceiptOutProductMapper receiptOutProductMapper;

    @Resource
    private OrgManagementMapper orgManagementMapper;

    @Resource
    private UserDataAuthMapper userDataAuthMapper;

    @Resource
    private UserManagementMapper userManagementMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductTypeMapper productTypeMapper;

    @Resource
    private PushManagementMapper pushMapper;

    @Override
    public BaseMapper<ReceiptOut> getMapper() {
        return mapper;
    }

    @Resource
    private ReceiptApplySonMapper sonMapper;

    @Resource
    private QwertMapper qwertMapper;

    private void qwertyu(CategoryProduct categoryProduct, ReceiptOutProduct receiptOutProduct) {
        if (categoryProduct.getProductNum() == null) {
            categoryProduct.setTotalPrice("0.00");
            categoryProduct.setProductNum(0);
            categoryProduct.setPrice("0.00");
        }
        Integer totalNum = categoryProduct.getProductNum() - receiptOutProduct.getNum();
        Float totalPrice = Float.parseFloat(categoryProduct.getTotalPrice()) -
                Float.parseFloat(receiptOutProduct.getTotalPrice());
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        String totalPrices = df.format(totalPrice);
        Qwert qwert = new Qwert();
        qwert.setBussinessDate(mapper.selectByPrimaryKey(receiptOutProduct.getReceiptId()).getBussinessDate());
        qwert.setCategoryId(categoryProduct.getCategoryId());
        qwert.setBeforeNum(categoryProduct.getProductNum());
        qwert.setBeforePrice(categoryProduct.getPrice());
        qwert.setBeforeTotalPrice(categoryProduct.getTotalPrice());
        qwert.setNumber(receiptOutProduct.getNumber());
        qwert.setCtime(DateUtil.now());
        qwert.setCuser(receiptOutProduct.getCuser());
        qwert.setProductId(receiptOutProduct.getProductId());
        qwert.setNum(receiptOutProduct.getNum());
        qwert.setPrice(receiptOutProduct.getPrice());
        qwert.setTotalPrice(receiptOutProduct.getTotalPrice());
        qwert.setAfterNum(totalNum);
        qwert.setAfterPrice(format);
        qwert.setAfterTotalPrice(totalPrices);
        qwertMapper.insertSelective(qwert);
    }


    private void qwertyui(CategoryProduct categoryProduct, ReceiptOutProduct receiptOutProduct) {
        if (categoryProduct.getProductNum() == null) {
            categoryProduct.setTotalPrice("0.00");
            categoryProduct.setProductNum(0);
            categoryProduct.setPrice("0.00");
        }
        Integer totalNum = categoryProduct.getProductNum() + receiptOutProduct.getNum();
        Float totalPrice = Float.parseFloat(categoryProduct.getTotalPrice()) +
                Float.parseFloat(receiptOutProduct.getTotalPrice());
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0.00";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        Qwert qwert = new Qwert();
        qwert.setBussinessDate(mapper.selectByPrimaryKey(receiptOutProduct.getReceiptId()).getBussinessDate());
        qwert.setCategoryId(categoryProduct.getCategoryId());
        qwert.setBeforeNum(categoryProduct.getProductNum());
        qwert.setBeforePrice(categoryProduct.getPrice());
        qwert.setBeforeTotalPrice(categoryProduct.getTotalPrice());
        qwert.setNumber("");
        qwert.setCtime(DateUtil.now());
        qwert.setCuser(receiptOutProduct.getCuser());
        qwert.setProductId(receiptOutProduct.getProductId());
        qwert.setNum(receiptOutProduct.getNum());
        qwert.setPrice(receiptOutProduct.getPrice());
        qwert.setTotalPrice(receiptOutProduct.getTotalPrice());
        qwert.setAfterNum(totalNum);
        qwert.setAfterPrice(format);
        qwert.setAfterTotalPrice(df.format(totalPrice));
        qwertMapper.insertSelective(qwert);
    }

    /**
     * 减库存
     *
     * @param categoryProduct
     * @param receiptOutProduct
     * @throws NumberFormatException
     */
    private synchronized void minusNum(CategoryProduct categoryProduct, ReceiptOutProduct receiptOutProduct) throws NumberFormatException {
        //计算总库存
        Integer totalNum = categoryProduct.getProductNum() - receiptOutProduct.getNum();
        if (totalNum < 0) {
            throw new LogicException("仓库：" + categoryMapper.selectByPrimaryKey(categoryProduct.getCategoryId()).getName() +
                    "下物品：" + productMapper.selectByPrimaryKey(categoryProduct.getProductId()).getName()
                    + "库存不足");
        }
        categoryProduct.setProductNum(totalNum);
        //计算出库后物品总价
//        Float totalPrice = Float.parseFloat(receiptOutProduct.getTotalPrice()) -
//                Float.parseFloat(categoryProduct.getTotalPrice());
//        categoryProduct.setTotalPrice(String.valueOf(totalPrice));

        Float price = Float.parseFloat(categoryProduct.getPrice());
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = df.format((float) price * totalNum);
        categoryProduct.setTotalPrice(format);
        categoryProductMapper.updateByPrimaryKeySelective(categoryProduct);
        //计算出库单总价
        String format1 = df.format((float) price * receiptOutProduct.getNum());
        receiptOutProduct.setTotalPrice(format1);
        receiptOutProduct.setPrice(categoryProduct.getPrice());
        receiptOutProductMapper.updateByPrimaryKeySelective(receiptOutProduct);
    }

    /**
     * 加库存
     *
     * @param categoryProduct
     * @param receiptOutProduct
     * @throws NumberFormatException
     */
    private synchronized void addNum(CategoryProduct categoryProduct, ReceiptOutProduct receiptOutProduct) throws Exception {
        //计算总库存
        Integer totalNum = categoryProduct.getProductNum() + receiptOutProduct.getNum();
        categoryProduct.setProductNum(totalNum);
        //计算入库后物品总价
        Float price = Float.parseFloat(categoryProduct.getPrice());
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = df.format((float) price * totalNum);
        categoryProduct.setTotalPrice(format);
//        Float totalPrice = Float.parseFloat(receiptOutProduct.getTotalPrice()) +
//                Float.parseFloat(categoryProduct.getTotalPrice());
//        categoryProduct.setTotalPrice(String.valueOf(totalPrice));
//        //计算入库后物品单价
//        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
//        String format = df.format((float) totalPrice / totalNum);
//        categoryProduct.setPrice(format);
        categoryProductMapper.updateByPrimaryKeySelective(categoryProduct);
    }

    /**
     * 推送提醒
     *
     * @param entity
     */
    private void confirmPush(ReceiptOut entity) {
        if (entity.getType() == 1) {
            int code = JpushClientUtil.sendToAsia(entity.getReceiveUser().split(","), "耗材管理", "耗材出库",
                    "耗材出库，单号：" + entity.getNumber() + "处理完成", "");
            PushManagement pu = new PushManagement();
            pu.setCompanyId(entity.getOrgId());
            pu.setContent("耗材出库，单号：" + entity.getNumber() + "处理完成");
            pu.setCtime(DateUtil.now());
            pu.setCuser(entity.getCuser());
            pu.setSender(entity.getReceiveUser());
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        }

    }


    public static void main(String[] args) {
        String a = "842f9097b198408d8bfae16f6ae7b163";
        int code = JpushClientUtil.sendToAsia(a.split(","), "耗材管理", "耗材出库",
                "耗材出库，单号：" + "123" + "处理完成", "");
        System.out.println(code);
    }

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Transactional
    public ReceiptOut add(ReceiptOut entity) throws Exception {
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        if (entity.getType() == 1) {
            entity.setNumber("CK" + TimeTool.getTimeDate14()+ RandomUtil.randomNumbers(5));
        } else {
            entity.setNumber("PK" + TimeTool.getTimeDate14()+ RandomUtil.randomNumbers(5));
        }
        entity.setSign(1);
        mapper.insertSelective(entity);
        //出库单-耗材关联新增
        List<ReceiptOutProduct> ReceiptOutProductList = entity.getReceiptOutProduct();
        for (ReceiptOutProduct receiptOutProduct : ReceiptOutProductList) {
            if (receiptOutProduct.getPrice().length() > 32) {
                throw new LogicException("单价超出最大长度32位");
            }
            if (receiptOutProduct.getTotalPrice().length() > 32) {
                throw new LogicException("总价超出最大长度32位");
            }
            receiptOutProduct.setNumber(entity.getNumber());
            receiptOutProduct.setCuser(entity.getCuser());
            receiptOutProduct.setReceiptId(entity.getId());
            receiptOutProductMapper.insertSelective(receiptOutProduct);
            //出库单-耗材库存修改
            Example example = new Example(CategoryProduct.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("categoryId", entity.getCategoryId());
            criteria.andEqualTo("productId", receiptOutProduct.getProductId());
            //库存表，不存在新增，存在改数
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example);
            if (0 == categoryProducts.size()) {
                log.info(receiptOutProduct.getProductId());
                throw new LogicException("选择的仓库下无此物品");
            } else {
                try {
                    //出库减、退库加
                    qwertyu(categoryProducts.get(0), receiptOutProduct);
                    minusNum(categoryProducts.get(0), receiptOutProduct);
                    confirmPush(entity);
                } catch (NumberFormatException e) {
                    log.error("金额格式错误");
                }
            }
        }
        return entity;
    }

    /**
     * 修改
     *
     * @param entity
     * @param flag
     * @return
     * @throws Exception
     */
    @Transactional
    public ReceiptOut edit(ReceiptOut entity, Boolean flag) throws Exception {
        //查询原出库单
        ReceiptOut receiptOut = mapper.selectByPrimaryKey(entity.getId());
        entity.setCuser(receiptOut.getCuser());
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getState() != 1) {
            throw new LogicException("仓库不可用");
        }
        if (StrUtil.isNotBlank(receiptOut.getReceiptApplyId())) {
            throw new LogicException("申请单关联的出库单不能修改");
        }
        UserManagement user = userManagementMapper.selectByPrimaryKey(entity.getUserId());
        if (user.getDataIsAll() == 2) {
            Example examples = new Example(UserDateAuth.class);
            Example.Criteria criterias = examples.createCriteria();
            criterias.andEqualTo("type", 4);
            criterias.andEqualTo("userId", entity.getUserId());
            List<UserDateAuth> userDateAuths = userDataAuthMapper.selectByExample(examples);
            Boolean validate = false;
            for (UserDateAuth userDateAuth : userDateAuths) {
                if (userDateAuth.getAuthId().equals(entity.getCategoryId())) {
                    validate = true;
                }
            }
            if (!validate) {
                throw new LogicException("仓库不可用");
            }
        }
        if (receiptOut.getSign() == 2) {
            throw new LogicException("出库单已签字");
        }
        Example exampleGetReceiptInProduct = new Example(ReceiptOutProduct.class);
        Example.Criteria criteriaGetReceiptInProduct = exampleGetReceiptInProduct.createCriteria();
        criteriaGetReceiptInProduct.andEqualTo("receiptId", entity.getId());
        List<ReceiptOutProduct> receiptOutProductList = receiptOutProductMapper.selectByExample(exampleGetReceiptInProduct);
        for (ReceiptOutProduct receiptOutProduct : receiptOutProductList) {
            receiptOutProduct.setCuser(entity.getUserId());
//            receiptOutProduct.setNum(receiptOutProduct.getNum() * -1);
            //查询当前出库单对应出库产品数量
            Integer num = receiptOutProduct.getNum();
            //查询当前该产品对应库存记录
            Example example = new Example(CategoryProduct.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("categoryId", receiptOut.getCategoryId());
            criteria.andEqualTo("productId", receiptOutProduct.getProductId());
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example);
            CategoryProduct categoryProduct = categoryProducts.get(0);
            //库存量加原出库库数量
            try {
                //是否是退库单
                qwertyui(categoryProducts.get(0), receiptOutProduct);
                addNum(categoryProduct, receiptOutProduct);
            } catch (Exception e) {
                log.error("金额格式错误");
            }
            //删除入库详情
            receiptOutProductMapper.deleteByPrimaryKey(receiptOutProduct.getId());

            //删除qwert
//            Example example2 = new Example(Qwert.class);
//            Example.Criteria criteria2 = example2.createCriteria();
//            criteria2.andEqualTo("productId", receiptOutProduct.getProductId());
//            criteria2.andEqualTo("number", receiptOut.getNumber());
//            qwertMapper.deleteByExample(example2);
        }
        while (flag) {
            mapper.updateByPrimaryKey(entity);
            return entity;
        }
        //删除原入库单
        mapper.deleteByPrimaryKey(entity.getId());
        //新增入库单、入库详情、更新库存量
        entity.setState(1);
        add(entity);
        return entity;
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional
    public ReceiptOut del(IdParams entity) throws Exception {

        Example exampleq = new Example(ReceiptApplySon.class);
        Example.Criteria criteriaq = exampleq.createCriteria();
        criteriaq.andEqualTo("receiptOutId", entity.getId());
        List<ReceiptApplySon> receiptApplySons = sonMapper.selectByExample(exampleq);
        if (receiptApplySons.size() != 0) {
            throw new LogicException("申请单关联的出库单不能删除");
        }
        ReceiptOut receiptOut = mapper.selectByPrimaryKey(entity.getId());
        if (categoryMapper.selectByPrimaryKey(receiptOut.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        if (receiptOut.getSign() == 2) {
            throw new LogicException("出库单已签字");
        }
        receiptOut.setState(2);
        receiptOut.setUserId(entity.getEuser());
        edit(receiptOut, true);
        return receiptOut;
    }

    /**
     * 分夜查询
     *
     * @param params
     * @return
     */
    public List<ReceiptOutGetPageNew> getPages(PageParams<ReceiptOutGetPageParams> params) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(params.getParams().getUserId());
        if (user.getDataIsAll() == 1) {
            params.getParams().setIsAdmin(1);
        } else {
            params.getParams().setIsAdmin(2);
        }
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptOutGetPageNew> pageList = mapper.getPage(params.getParams());
        return pageList;
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    public ReceiptOut view(String id) {
        ReceiptOut receiptOut = mapper.selectByPrimaryKey(id);
        receiptOut.setCategoryName(categoryMapper.selectByPrimaryKey(receiptOut.getCategoryId()).getName());
        receiptOut.setCuserName(userManagementMapper.selectByPrimaryKey(receiptOut.getCuser()).getName());
        Example example = new Example(ReceiptOutProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiptId", id);
        List<ReceiptOutProduct> receiptOutProductList = receiptOutProductMapper.selectByExample(example);
        for (ReceiptOutProduct receiptOutProduct : receiptOutProductList) {
            Product product = productMapper.selectByPrimaryKey(receiptOutProduct.getProductId());
            product.setTypeName(productTypeMapper.selectByPrimaryKey(product.getType()).getName());
            receiptOutProduct.setProduct(product);
        }
        receiptOut.setReceiptOutProduct(receiptOutProductList);
        return receiptOut;
    }

    public ReceiptOut sign(ReceiptOut entity) {
        ReceiptOut receiptOut = mapper.selectByPrimaryKey(entity.getId());
        if (receiptOut.getSign() == 2) {
            throw new LogicException("出库单已签字");
        }
        receiptOut.setSignImg(entity.getSignImg());
        receiptOut.setSign(2);
        receiptOut.setEtime(DateUtil.now());
        mapper.updateByPrimaryKeySelective(receiptOut);
        if (StrUtil.isNotBlank(receiptOut.getReceiptApplyId())) {
            ReceiptApplySon receiptApplySon = sonMapper.selectByPrimaryKey(receiptOut.getReceiptApplyId());
            receiptApplySon.setConfirm(2);
            receiptApplySon.setConfirmUser(entity.getUserId());
            receiptApplySon.setConfirmTime(DateUtil.now());
            sonMapper.updateByPrimaryKeySelective(receiptApplySon);
        }
        return receiptOut;
    }

    public List<ReceiptOutCheckExtend> printCheck(String ids) {
        List<ReceiptOutCheckExtend> list = mapper.selByIdsCheck(Arrays.asList(ids.split(",")));
        if (list != null && list.size() > 0) {
            for (ReceiptOutCheckExtend extend : list) {
                List<ReceiptMoveProductExtend> receiptMoveProductList = mapper.getReceiptMoveExtend(extend.getId());
                extend.setReceiptMoveProductList(receiptMoveProductList);
            }
        }
        return list;
    }

    public List<ReceiptOutExtend> print(String ids) {
        List<ReceiptOutExtend> list = mapper.selByIds(Arrays.asList(ids.split(",")));
        if (list != null && list.size() > 0) {
            for (ReceiptOutExtend extend : list) {
                List<ReceiptMoveProductExtend> receiptMoveProductList = mapper.getReceiptMoveExtend(extend.getId());
                extend.setReceiptMoveProductList(receiptMoveProductList);
            }
        }
        return list;
    }

    public List<ReceiptOutCheck> exportCheck(ReceiptOutGetPageParams params) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(params.getUserId());
        if (user.getDataIsAll() == 1) {
            params.setIsAdmin(1);
        } else {
            params.setIsAdmin(2);
        }
        List<ReceiptOutCheck> list = mapper.exportCheck(params);
        for (ReceiptOutCheck receiptOutCheck : list) {
            receiptOutCheck.setList(mapper.getPageExport(receiptOutCheck.getId()));
        }
        return list;
    }

    public List<ReceiptOutExport> export(ReceiptOutGetPageParams params) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(params.getUserId());
        if (user.getDataIsAll() == 1) {
            params.setIsAdmin(1);
        } else {
            params.setIsAdmin(2);
        }
        List<ReceiptOutExport> list = mapper.export(params);
        for (ReceiptOutExport receiptOutExport : list) {
            if (receiptOutExport.getType() == 1) {
                receiptOutExport.setType1("出库");
            } else {
                receiptOutExport.setType1("退库");
            }
            receiptOutExport.setList(mapper.getPageExport(receiptOutExport.getId()));
        }
        return list;
    }
}
